<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="报告名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入报告名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['member:presentation:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="报告名称" align="left" prop="name" />
      <el-table-column label="开始时间" prop="startTime" width="180"/>
      <el-table-column label="结束时间" prop="endTime" width="180"/>
      <el-table-column
        label="创建时间"
        align="left"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="280px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['member:presentation:update']"
          >
            编辑
          </el-button>
          <el-button
            type="primary"
            link
            size="small"
            @click.stop="handleShowPersonList(scope.row)"
            class="add-btn"
          >
            相关人员
          </el-button>
          <el-button
            link
            type="primary"
            @click="previewPresentation(scope.row.id)"
            v-hasPermi="['member:presentation:preview']"
          >
            预览
          </el-button>
          <el-button
            link
            type="primary"
            @click="downloadPresentation(scope.row.id, scope.row.name)"
          >
            报告
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['member:presentation:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <el-drawer
    v-model="showPersonListDrawer"
    title="添加预警人员"
    direction="rtl"
    size="50%"
  >
    <!-- 标题下方的阴影分隔线 -->
    <div class="header-divider"></div>

    <!-- 人员列表组件 -->
    <PersonListDrawer
      ref="personListRef"
      :presentation-id="currentRow?.id!"
      @cancel="showPersonListDrawer = false"
    />
  </el-drawer>

  <!-- 表单弹窗：添加/修改 -->
  <PresentationForm ref="formRef" @success="getList" />

  <!-- 预览弹窗 -->
  <el-dialog
    title="报告预览"
    v-model="previewVisible"
    width="80%"
    :close-on-click-modal="false"
    :max-height="`90vh`"
    class="preview-dialog"
  >
    <div v-loading="previewLoading" class="preview-content">
      <div v-html="previewContent"></div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineExpose } from 'vue'
import { dateFormatter } from '@/utils/formatTime'
import { PresentationApi, PresentationVO } from '@/api/member/presentation'
import PresentationForm from './PresentationForm.vue'
import { useI18n } from 'vue-i18n'
import {useMessage} from "@/hooks/web/useMessage";
import Icon from "../../../components/Icon/src/Icon.vue";
import PersonListDrawer from "@/views/member/presentation/components/PersonListDrawer.vue";

/** 报告 列表 */
defineOptions({ name: 'Presentation' })

// 控制抽屉显示
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<PresentationVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  remark: undefined
})
const queryFormRef = ref() // 搜索的表单
const formRef = ref() // 表单组件引用

// 预览相关
const previewVisible = ref(false)
const previewLoading = ref(false)
const previewContent = ref('')

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PresentationApi.getPresentationPage(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    message.error('获取报告列表失败')
    console.error('获取报告列表失败:', error)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const showPersonListDrawer = ref(false);
const personListRef = ref<InstanceType<typeof PersonListDrawer>>();
const currentRow = ref<PresentationVO | null>(null);

// 打开涉及人员抽屉
const handleShowPersonList = (row: PresentationVO) => {
  // 关键：添加非空校验
  if (!row || !row.id) {
    message.error('无效的报告数据，无法打开人员列表')
    return
  }
  currentRow.value = row;
  showPersonListDrawer.value = true;
  // 可以在这里直接触发数据刷新（如果子组件提供了方法）
  nextTick(() => {
    personListRef.value?.fetchPersonList(row.id);
  });
};

/** 预览操作 */
const previewPresentation = async (id: number) => {
  try {
    previewLoading.value = true
    const data = await PresentationApi.getPresentation(id)
    // 假设内容存储在某个字段，这里根据实际情况调整
    previewContent.value = data.content || '<p>无内容</p>'
    previewVisible.value = true
  } catch (error) {
    message.error('预览报告失败')
    console.error('预览报告失败:', error)
  } finally {
    previewLoading.value = false
  }
}

/** 下载操作 */
const downloadPresentation = async (id: number, fileName: string) => {
  try {
    await PresentationApi.downloadPresentation(id, `${fileName}.doc`)
    message.success('下载成功')
  } catch (error) {
    message.error('下载失败')
    console.error('下载失败:', error)
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PresentationApi.deletePresentation(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})

defineExpose({
  getList
})
</script>

<style scoped>
.preview-dialog {
  .el-dialog__body {
    padding: 20px;
    max-height: calc(90vh - 100px);
    overflow-y: auto;
  }
}

.preview-content {
  line-height: 1.8;
  font-size: 16px;

  h1, h2, h3, h4, h5, h6 {
    margin: 16px 0 8px;
    font-weight: bold;
  }

  p {
    margin-bottom: 12px;
  }

  img {
    max-width: 100%;
    height: auto;
  }

  table {
    width: 100%;
    border-collapse: collapse;
    margin: 16px 0;
  }

  table td, table th {
    border: 1px solid #ddd;
    padding: 8px 12px;
  }

  ul, ol {
    margin: 12px 0;
    padding-left: 24px;
  }
}
</style>
